<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel">
    <el-form ref="deptForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeeSimple">
          <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    // 校验名称是否有重复
    const checkNameRepeat = async(rule, value, callback) => { // 参数是固定写法，而且不用return
      const { depts } = await getDepartments()
      if (this.formData.id) {
        // 编辑
        const isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id).some(item => item.name === value && value)
        isRepeat ? callback(new Error(`同级部门已经有${value}了`)) : callback()
      } else {
        // 新增
        const isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value && value)// 判断是否与子元素有重名
        isRepeat ? callback(new Error(`同级部门已经有${value}了`)) : callback()
      }
    }
    // 校验code是否有重复
    const checkCodeRepeat = async(rule, value, callback) => { // 参数是固定写法，而且不用return
      const { depts } = await getDepartments()
      if (this.formData.id) {
        // 编辑
        const isRepeat = depts.filter(item => item.id !== this.treeNode.id).some(item => item.code === value && value)
        isRepeat ? callback(new Error(`组织架构下已经有${value}了`)) : callback()
      } else {
        // 新增
        const isRepeat = depts.some(item => item.code === value && value)// 判断是否有相同code
        isRepeat ? callback(new Error(`组织架构下已经有${value}了`)) : callback()
      }
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { max: 50, message: '长度需要在1-50字符内', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }], // 固定写法不用传参
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { max: 50, message: '长度需要在1-50字符内', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { max: 300, message: '长度需要在1-300字符内', trigger: 'blur' }]
      },
      peoples: []// 员工列表
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple()
    },
    async getDepartDetail(id) { // 获取详情方法，由于props是异步的，因此要在父组件调用此方法避免错误
      this.formData = await getDepartDetail(id)// 得到的formData会有id属性，可以以此区分出编辑与新增
    },
    btnOK() {
      this.$refs.deptForm.validate(async isOK => { // 表单校验
        if (isOK) {
        // 校验通过
          if (this.formData.id) {
            // 编辑
            await updateDepartments(this.formData)
          } else {
            // 新增
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }
          this.$emit('addDepts')// 重新渲染列表
          this.btnCancel()
        }
      })
    },
    btnCancel() { // 关闭弹窗
      this.$emit('update:showDialog', false)// 父组件用sync修饰传值的固定写法，针对用props控制的弹窗
    }
  }
}
</script>

<style>

</style>
